<?php

namespace app\api\controller;

use app\admin\model\Xcx;
use think\Db;

/**
 * 工具类
 */
class Utils extends Base
{

    /**
     * 随机的从数据库表格中取出若干数据
     * @param int $num 需要抽取的默认条数
     * @param string $table 需要抽取的数据表
     * @return array
     */
    public function get_rand($num, $table)
    {
        $res = array();
        while (count($res) < $num) {
            $lack = $num - count($res);
            $list = $this->get_rand_arr_from_table($lack, $table);
            $res = array_merge($res, $list);
        }
        return $res;
    }

    public function get_rand_arr_from_table($num, $table)
    {
        $countcus = Db::name($table)->count();    // 获取总记录数
        $max = Db::name($table)->max('id'); // 统计某个字段最大数据
        $min = Db::name($table)->min('id'); // 统计某个字段最小数据
        if ($countcus < $num) {
            $num = $countcus;
        }
        $i = 1;
        $flag = 0;
        $arr = array();
        while ($i <= $num) {
            $rundnum = mt_rand($min, $max);//抽取随机数
            if ($flag != $rundnum) {
                //过滤重复
                if (!in_array($rundnum, $arr)) {
                    $arr[] = $rundnum;
                    $flag = $rundnum;
                } else {
                    $i--;
                }
                $i++;
            }
        }
        $list = Db::name($table)->where('id', 'in', $arr, 'or')->select();
        return $list;
    }

    /**
     * 把秒数转换为时分秒的格式
     * @param Int $times 时间，单位 秒
     * @return String   '00:00'
     */
    public function sec_to_time($times)
    {
        $result = '00:00';
        if ($times > 0) {
            $minute = floor($times / 60);
            $second = floor(($times - 60 * $minute) % 60);
            $result = ($minute >= 10 ? $minute : '0' . $minute) . ':' . ($second >= 10 ? $second : '0' . $second);
        }
        return $result;
    }

    /**
     * 获取openid
     * @param \app\common\controller\小程序原始id $gh_id
     * @param \app\common\controller\用户code $code
     * @return bool|mixed
     * @throws \think\exception\DbException
     */
    public function get_openid($gh_id, $code)
    {
        $xcx = Xcx::get(['ghid' => $gh_id]);

        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $params['appid'] = $xcx['appid'];
        $params['secret'] = $xcx['secret'];
        $params['js_code'] = $code;
        $params['grant_type'] = 'authorization_code';

        // 请求微信后台获取openid
        $res = $this->http($url, $params);
        $data = json_decode($res, true);
        // Log::record($data);
        if (array_key_exists('openid', $data)) {
            return $data['openid'];
        } else {
            return false;
        }
    }

}
